import React from 'react';
import { Spin, message } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getJobAndQuestionInfo } from '@/pages/RecruitEmail/service/interview';
import {
    InterviewRemindMobile,
    InterviewQuestionMobile,
    UploadMobile,
    Result,
    Button
} from '@/pages/RecruitEmail/mobile/components';
import submitWorkImage from '@/pages/RecruitEmail/images/interview-bg-new.png';
import { saveWork } from '@/pages/RecruitEmail/service';
import cn from 'classnames';
import { STATUS } from '@/pages/RecruitEmail/constants';
import { pushRoute } from '@/pages/RecruitEmail/utils';
import styles from './index.less';

export default function InterviewHomeWork({ nid, id }) {
    //
    const [isSubmit, setIsSubmit] = React.useState(false);
    // const { id = '' } = query;
    const [fileList, setFileList] = React.useState([]);
    const [submitLoading, setSubmitLoading] = React.useState(false);

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [uploading, setUploading] = React.useState(false);
    const titleData = {
        imageUrl: submitWorkImage,
        subTitle: '请提交您的面试作业'
    };
    const { data: result, loading: questionLoading, run: getJobAndQuestion } = useRequest(
        () => getJobAndQuestionInfo(nid),
        {
            manual: true,
            initialData: [],
            ...defaultFormatResult
        }
    );
    // 查看面试作业
    React.useEffect(() => {
        getJobAndQuestion();
    }, []);
    React.useEffect(() => {
        if (result) {
            if (result?.state === 2) {
                setIsSubmit(true);
            } else {
                setIsSubmit(false);
            }
        }
    }, [result]);

    const handleCheck = () => {
        pushRoute({
            pathname: '/recruitment/register',
            query: {
                id,
                nid
            }
        });
    };

    const uploadData = {
        fileList,
        maxNum: 5,
        changeFileList: _fileList => {
            if (_fileList && _fileList.length <= 5) {
                setFileList(_fileList);
            } else {
                message.error('最多只能上传五个附件');
            }
        },
        removeFile: (uid, _fileList) => {
            const list = _fileList.filter(m => m.uid !== uid);
            setFileList(list);
        },
        showErr: e => {
            console.log(e);
            message.error('提交失败，请检查您的网络连接');
        },
        onChange: changeData => {
            setUploading(changeData.fileList.some(item => item.status !== 'done'));
        }
    };
    const handleSubmit = async () => {
        // setSubmitLoading(true);
        // 提交逻辑
        if (fileList.length === 0) {
            message.error('请上传作业');
        } else {
            setSubmitLoading(true);
            // 过滤出错文件
            const list = fileList.filter(m => m.status !== 'error');
            const finalList = list.map(item => ({
                id: item.uid,
                url: item.response ? item.response : item.url,
                name: item.name
            }));
            const uploadFileArray = fileList.length > 0 ? finalList : '';

            const dto = {
                answerFileUrl: JSON.stringify(uploadFileArray),
                arrangeId: result?.arrangeId,
                id: result?.id
            };
            try {
                const resultSubmit = await saveWork(dto);
                const { code, msg } = resultSubmit;
                if (code === 10000) {
                    setSubmitLoading(false);
                    getJobAndQuestion();
                    // history.push({
                    //     pathname: '/external/interview/submitworkresult',
                    //     query: { state: 1, companyName }
                    // });
                } else {
                    setSubmitLoading(false);
                    message.error(msg);
                }
            } catch (error) {
                console.log(error);
                setSubmitLoading(false);
                message.error('提交失败，请检查您的网络连接');
            }
        }
    };

    const list = React.useMemo(() => {
        let resultList = [];
        if (result) {
            // 已提交面试作业
            if (isSubmit) {
                resultList = [
                    {
                        key: '面试岗位：',
                        value: result?.duteName
                    },
                    {
                        key: '面试轮次：',
                        value: result?.interviewRoundName
                    },
                    {
                        key: '面试方式：',
                        value: '面试作业'
                    },
                    {
                        key: '面试题目：',
                        value: result?.topicInfo,
                        isMore: true,
                        id: 1
                    },
                    {
                        key: '截止时间：',
                        value: result?.deadline
                    }
                ];
            } else {
                resultList = [
                    {
                        key: '面试岗位：',
                        value: result?.duteName
                    },

                    {
                        key: '面试题目：',
                        value: result?.topicInfo,
                        isMore: true,
                        id: 2
                    }
                ];
            }
        }
        return resultList;
    }, [result, isSubmit]);
    return (
        <div className={styles.interviewMobile}>
            <div className={styles.fakeItem} style={isSubmit ? { background: '#fff' } : {}}></div>

            <div className={cn({ [styles.resultWrap]: !isSubmit })}>
                <Spin spinning={questionLoading}>
                    <div style={isSubmit ? { background: '#fff' } : {}}>
                        {isSubmit ? (
                            <>
                                <Result
                                    type={STATUS.ACCEPT}
                                    title="已提交面试作业"
                                    content="为避免影响您后续面试，请您于面试前，尽快完善《应聘登记表》"
                                />
                                <div className={styles.ph16}>
                                    <Button type="primary" onClick={handleCheck}>
                                        立即完善
                                    </Button>
                                </div>
                            </>
                        ) : (
                            <InterviewRemindMobile {...titleData} />
                        )}
                    </div>
                    <div className={cn({ [styles.con]: !isSubmit, [styles.con1]: isSubmit })}>
                        {isSubmit && <div className={styles.interviewInfo}>面试信息</div>}
                        <InterviewQuestionMobile list={list} rows={4}/>
                        {!isSubmit && (
                            <>
                                <UploadMobile {...uploadData} />
                                <div className={styles.bDiv}></div>
                                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                                    提交
                                </Button>
                            </>
                        )}
                    </div>
                </Spin>
            </div>
            {/* <BottomActionWrap>
                    <Button type="primary" loading={uploading} className={styles.submitBtn} onClick={handleSubmit}>
                        提交
                    </Button>
                </BottomActionWrap> */}
        </div>
    );
}
